import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jyofservice/fluro/NavigatorUtil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:jyofservice/bean/order_person_entity.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/DiaoDuNotification.dart';

class RightEndDrawer extends StatefulWidget {
  @override
  _RightEndDrawerState createState() => _RightEndDrawerState();
}

class _RightEndDrawerState extends State<RightEndDrawer> {
  final _lshController = TextEditingController();
  final lxrController = TextEditingController();
  final lxrPhoneController = TextEditingController();
  final incomingNumController = TextEditingController();
  final addressController = TextEditingController();
  String? startTime;
  String? endTime;
  late SharedPreferences sharedPreferences;
  String? key;
  List<DropdownMenuItem> list = [];
  List<DropdownMenuItem> sourceList = [];
  List<DropdownMenuItem> isYqList = [];
  int? personId;
  String? personName;
  int? sourceId;
  String? sourceName;
  late OrderPersonEntity orderPersonData;
  late OrderPersonEntity sourceData;
  String? isYqName;

  List isYqData = [{'name':'全部'},{'name':'是'},{'name':'否'}];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init().then((onValue) {
      if (onValue != null) {
        getOrderPersonData();
        getOrderSourceData();
      }
    });

    //是否超时
    isYqList = new List<DropdownMenuItem>.generate(
        isYqData.length,
            (i) => new DropdownMenuItem(
            child: new Text(
              isYqData[i]['name'] ?? "",
              style: TextStyle(
                  color: Colors.black87,
                  fontSize: ScreenUtil().setSp(35)),
            ),
            value:isYqData[i]['name'] ?? ""));
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Column(
        children: <Widget>[
          AppBar(
            centerTitle: true,
            title: Text(
              '筛选',
              style: TextStyle(
                  color: Colors.white, fontSize: ScreenUtil().setSp(45)),
            ),
            actions: <Widget>[
              SizedBox(
                width: 30,
              )
            ],
          ),
          Container(
            width: ScreenUtil().scaleWidth,
            height: ScreenUtil().setHeight(2),
            color: Colors.grey,
          ),
          Expanded(
            flex: 1,
            child: Container(
              color: Colors.white,
              padding: EdgeInsets.all(10),
              child: SingleChildScrollView(
                  child: Column(
                children: <Widget>[
                  getRow('收费编码：', '请输入收费编码', _lshController),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        '开始时间:',
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil().setSp(35)),
                      ),
                      SizedBox(
                        width: ScreenUtil().setWidth(10),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          height: ScreenUtil().setHeight(80),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(5)),
                            border: Border.all(color: Colors.grey),
                          ),
                          child: Row(
                            children: <Widget>[
                              TextButton(
                                onPressed: () {
                                  DatePicker.showDateTimePicker(context,
                                      showTitleActions: true,
                                      onChanged: (date) {
                                    print('change $date');
                                  }, onConfirm: (date) {
                                    print('confirm $date');
                                    if (mounted) {
                                      setState(() {
                                        startTime =
                                            date.toString().substring(0, 19);
                                      });
                                    }
                                  },
                                      currentTime: DateTime.now(),
                                      locale: LocaleType.zh);
                                },
                                child: Text(
                                  startTime ?? '请 选 择 开 始 时 间',
                                ),
                              ),
                              Offstage(
                                offstage: startTime == null ? false : true,
                                child: Icon(Icons.arrow_drop_down),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: ScreenUtil().setHeight(20),
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        '结束时间:',
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil().setSp(35)),
                      ),
                      SizedBox(
                        width: ScreenUtil().setWidth(10),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          height: ScreenUtil().setHeight(80),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(5)),
                            border: Border.all(color: Colors.grey),
                          ),
                          child: Row(
                            children: <Widget>[
                              TextButton(
                                onPressed: () {
                                  DatePicker.showDateTimePicker(context,
                                      showTitleActions: true,
                                      onChanged: (date) {
                                    print('change $date');
                                  }, onConfirm: (date) {
                                    print('confirm $date');
                                    if (mounted) {
                                      setState(() {
                                        endTime =
                                            date.toString().substring(0, 19);
                                      });
                                    }
                                  },
                                      currentTime: DateTime.now(),
                                      locale: LocaleType.zh);
                                },
                                child: Text(
                                  endTime ?? '请 选 择 结 束 时 间',
                                ),
                              ),
                              Offstage(
                                offstage: endTime == null ? false : true,
                                child: Icon(Icons.arrow_drop_down),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  getRow('联 系 人：', '请输入联系人', lxrController),
                  getRow('联系电话：', '请输入联系电话', lxrPhoneController),
                  getRow('来电号码：', '请输入来电号码', incomingNumController),
                  getOrderPerson(),
                  getOrderSource(),
                  getIsYqRow(),
                  getRow('详细地址：', '请输入详细地址', addressController),
                ],
              )),
            ),
          ),
          Container(
            color: Colors.white,
            margin: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
            alignment: Alignment.bottomCenter,
            child: Row(
              children: <Widget>[
//                Expanded(
//                  child: Container(
//                      decoration: BoxDecoration(
//                          border:
//                              Border.all(width: 1.0, color: Color(0xff4c8eff)),
//                          color: Colors.white),
//                      height: 60.0,
//                      child: FlatButton(
//                        child: Text(
//                          "重置",
//                          style: TextStyle(
//                              color: const Color(0xFF3090ff),
//                              fontSize: ScreenUtil().setSp(28)),
//                        ),
//                        onPressed: () {
//                          startTime = null;
//                          endTime = null;
//                          _lshController.clear();
//                          lxrController.clear();
//                          lxrPhoneController.clear();
//                          incomingNumController.clear();
//                          addressController.clear();
////                          personName = "";
////
////                          personId = null;
////                          sourceName = "";
////                          sourceId = null;
//                          if (mounted) {
//                    setState(() {});}
//                        },
//                      )),
//                ),
                Expanded(
                  child: Container(
                      decoration: BoxDecoration(
                        border:
                            Border.all(width: 1.0, color: Color(0xff4c8eff)),
                        color: Color(0xff4c8eff),
                      ),
                      height: 60.0,
                      child: TextButton(
                        child: Text(
                          "查询",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil().setSp(28)),
                        ),
                        onPressed: () {
                          _chaxun();
                        },
                      )),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  //收费编码等水平widget
  Widget getRow(
      String title, String hitText, TextEditingController controller) {
    return Container(
      padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text('$title',
              style: TextStyle(
                  color: Colors.black87, fontSize: ScreenUtil().setSp(35))),
          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.only(left: 5),
              height: ScreenUtil().setHeight(80),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                border: Border.all(color: Colors.grey),
              ),
              child: TextField(
                decoration: InputDecoration(
                  hintText: '$hitText',
                  border: InputBorder.none,
                ),
                controller: controller,
              ),
            ),
          )
        ],
      ),
    );
  }

  //工单来源widget
  Widget getOrderSource() {
    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '工单来源：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: sourceName,
                items: sourceList,
                hint: Text('请选择工单来源'),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      sourceName = T;
                      for (int i = 0; i < sourceData.data!.length; i++) {
                        if (sourceData.data![i].name == sourceName) {
                          sourceId = sourceData.data![i].iD;
                        }
                      }
                    });
                  }
                },
                style: new TextStyle(
                    //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);
  }

  //是否超时
  Widget getIsYqRow() {
    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '是否超时：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: isYqName,
                items: isYqList,
                hint: Text('请选择是否超时'),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      isYqName = T;
                    });
                  }
                },
                style: new TextStyle(
                  //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);
  }

  //下单人员widgett
  Widget getOrderPerson() {
    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理人员：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: personName,
                items: list,
                hint: Text('请选择处理人员'),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      personName = T;

                      for (int i = 0; i < orderPersonData.data!.length; i++) {
                        if (orderPersonData.data![i].name == personName) {
                          personId = orderPersonData.data![i].iD;
                        }
                      }
                    });
                  }
                },
                style: new TextStyle(
                    //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);
  }

  Future init() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    return key;
  }

  //获取下单人员数据
  Future getOrderPersonData() async {
    list.clear();
    String aesData= await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "XiaDanRenYuan",
      "wherestr": "1=1",
      "idstr": "ID",
      "namestr": "Name","ClientType":"phone","ClientKey":aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getchoosedata",
        data: data);
    orderPersonData = OrderPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (orderPersonData.code == "200") {
      if (mounted) {
        setState(() {
          list = new List<DropdownMenuItem>.generate(
              orderPersonData.data!.length,
                  (i) =>
              new DropdownMenuItem(
                  child: new Text(
                    orderPersonData.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: orderPersonData.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

  //获取下单来源数据
  Future getOrderSourceData() async {
    sourceList.clear();
    String aesData= await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "vw_GD_fromtype_basic",
      "wherestr": "1=1",
      "idstr": "ID",
      "namestr": "Name","ClientType":"phone","ClientKey":aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getchoosedata",
        data: data);
    sourceData = OrderPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (sourceData.code == "200") {
      if (mounted) {
        setState(() {
          sourceList = new List<DropdownMenuItem>.generate(
              sourceData.data!.length,
                  (i) =>
              new DropdownMenuItem(
                  child: new Text(
                    sourceData.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: sourceData.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

  void _chaxun() {
    String whereStr = "";
    print("lsh:" + _lshController.text.toString());

    if (_lshController.text.toString().length != 0) {
      whereStr = " and Sfbm like '%" + (_lshController.text.toString()) + "%'";
    }
    if (startTime != null) {
      whereStr += " and CreateDate >= '" + (startTime ?? "") + "'";
    }
    if (endTime != null) {
      whereStr += " and CreateDate <= '" + (endTime ?? "") + "'";
    }
    if (lxrController.text.toString().length != 0) {
      whereStr += " and Link_man like '%" +
          (lxrController.text.toString() ?? "") +
          "%'";
    }

    if (lxrPhoneController.text.toString().length != 0) {
      whereStr += " and Link_phone like '%" +
          (lxrPhoneController.text.toString() ?? "") +
          "%'";
    }
    if (incomingNumController.text.toString().length != 0) {
      whereStr += " and ComePhone like '%" +
          (incomingNumController.text.toString() ?? "") +
          "%'";
    }
    if (personId != null) {
      whereStr += " and User_id =" + (personId.toString() ?? "");
    }
    if (sourceId != null) {
      whereStr += " and FromType =" + (sourceId.toString() ?? "");
    }
    if(isYqName!=null&&isYqName!='全部') {
      whereStr += " and ifyq =" +"'"+ isYqName!+"'";
    }
    if (addressController.text.toString().length != 0) {
      whereStr += " and All_name like '%" +
          (addressController.text.toString() ?? "") +
          "%'";
    }
    if (whereStr.length == 0) {
      whereStr = "1=1";
    } else if (whereStr.startsWith(" and ")) {
      whereStr = whereStr.substring(5);
    }
    print(whereStr);

    DiaoDuNotification(wherestr: whereStr).dispatch(context);
    NavigatorUtil.goBack(context);
  }
}
